package com.travel.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.travel.commons.annotation.SysLog;
import com.travel.commons.shiro.ShiroUserGetter;
import com.travel.commons.utils.*;
import com.travel.commons.validator.ValidatorUtils;
import com.travel.commons.validator.groups.AddGroup;
import com.travel.commons.validator.groups.UpdateGroup;
import com.travel.modules.asset.dto.ParentScenicArea;
import com.travel.modules.asset.entity.Goods;
import com.travel.modules.asset.entity.ScenicArea;
import com.travel.modules.asset.service.GoodsService;
import com.travel.modules.asset.service.ScenicAreaService;
import com.travel.modules.sys.service.SysConfigService;
import com.travel.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/scenicarea")
public class SysScenicAreaController {
    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private ScenicAreaService scenicAreaService;

    @Resource
    private GoodsService goodsService;

    @RequestMapping("/list")
    public R list(@RequestBody Map<String, Object> param) {
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        if (page == null || limit == null) {
            return R.error("缺少分页参数");
        }
        List<ScenicArea> list = scenicAreaService.getAllScenicArea(param);
        return R.ok().put("page", PageUtils.getPage(list, limit, page));
    }

    @RequestMapping("/list/current")
    public R list2Current(@RequestBody Map<String, Object> param) {
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        if (page == null || limit == null) {
            return R.error("缺少分页参数");
        }
        param.put("userId", ShiroUserGetter.getUserId());
        List<ScenicArea> list = scenicAreaService.getAllScenicArea(param);
        return R.ok().put("page", PageUtils.getPage(list, limit, page));
    }

    @RequestMapping("/list/basearea")
    public R baseArea() {
        List<ParentScenicArea> list = scenicAreaService.getParentArea();
        return R.ok().put("page", list);
    }

    /**
     * 景点详情
     * @param form areaId
     */
    @RequestMapping("/info")
    public R info(@RequestBody ScenicArea form) {
        String areaId = form.getAreaId();
        if (areaId == null) {
            return R.error("缺少area_id");
        }
        ScenicArea scenicArea = scenicAreaService.getOne(new QueryWrapper<ScenicArea>().eq("area_id", areaId));
        return R.ok().put("page", scenicArea);
    }

    @SysLog("景点添加")
    @RequestMapping("/add")
    public R add(@RequestBody ScenicArea form) {
        String parentAddr = form.getParentAreaName();
        ScenicArea parentArea = scenicAreaService.getOne(new QueryWrapper<ScenicArea>().eq("name", parentAddr));
        if (parentArea == null) {
            return R.error("所属地区不存在");
        }

        parentArea.setSpotCount(parentArea.getSpotCount() + 1);
        form.setParentAreaId(parentArea.getId());
        form.setAreaId(Constant.AREA_CODE.get(parentArea.getName()) + "-" + new SnowNoGenerator().generate());
        form.setUserId(ShiroUserGetter.getUserId());
        form.setStatus(0);
        if (ShiroUserGetter.getUser().getRoleId() == 1) {
            form.setStatus(1);
        }
        form.setHot(0);
        ValidatorUtils.validate(form, AddGroup.class);

        scenicAreaService.save(form);
        scenicAreaService.updateById(parentArea);
        log.warn("用户: {}, 景点添加， 编号 : {}", ShiroUserGetter.getUser().getId(), form.getAreaId());
        return R.ok().put("page", form)
                .put("id", form.getAreaId());
    }

    /**
     * 更新景点信息
     * @param form
     */
    @SysLog("景点编辑")
    @RequestMapping("/edit")
    public R edit(@RequestBody ScenicArea form) {
        ScenicArea old = scenicAreaService.getById(form.getId());
        if (old == null) {
            return R.error("更新目标丢失");
        }
        if (StringUtils.isNotBlank(form.getParentAreaName())) {
            ScenicArea parentArea = scenicAreaService.getOne(new QueryWrapper<ScenicArea>().eq("name", form.getParentAreaName()));
            form.setParentAreaId(parentArea.getId());
        }
        form.setAreaId(null);
        BeanUtils.copyProperties(form, old);
        ValidatorUtils.validate(old, UpdateGroup.class);
        scenicAreaService.updateById(old);
        if (old.getStatus() != 1) {
            goodsService.remove(new QueryWrapper<Goods>().eq("goods_id", old.getAreaId()));
        } else {
            goodsService.save(Goods.builder().goodsId(form.getAreaId()).tableName(Constant.T_SCENIC_AREA).build());
        }
        log.warn("用户: {}, 景点更新， 编号 : {}", ShiroUserGetter.getUser().getId(), form.getAreaId());
        return R.ok().put("id", old.getAreaId());
    }

    /**
     * 删除指定的景点
     * @param param areaId - 景点id
     */
    @SysLog("景点删除")
    @RequestMapping("/del")
    public R del(@RequestBody Map<String, String> param) {
        String areaId = param.get("areaId");
        if (StringUtils.isBlank(areaId)) {
            return R.error("缺少id");
        }
        ScenicArea area = scenicAreaService.getOne(new QueryWrapper<ScenicArea>().eq("area_id", areaId));
        if (area == null) {
            return R.error("没有该记录");
        }
        if (area.getParentAreaId() == 0) {
            return R.error("该记录不可删除");
        }
        /* 更新父级地区的景点数 */
        ScenicArea parentArea = scenicAreaService.getById(area.getParentAreaId());
        parentArea.setSpotCount(parentArea.getSpotCount() - 1);
        scenicAreaService.updateById(parentArea);

        goodsService.remove(new QueryWrapper<Goods>().eq("goods_id", areaId));
        scenicAreaService.removeById(area.getId());
        log.warn("用户：{}, 景点删除, 编号: {}", ShiroUserGetter.getUser().getId(), areaId);
        return R.ok().put("id", areaId);
    }
}
